- Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathQueueUsingStackEnqueueEfficient.java
53 lines (39 loc) Β· 867 Bytes
/
QueueUsingStackEnqueueEfficient.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
packagesection11_Queue;
importjava.util.Stack;
publicclassQueueUsingStackEnqueueEfficient {
Stack<Integer> primary;
Stack<Integer> secondary;
publicQueueUsingStackEnqueueEfficient() {
primary = newStack<Integer>();
secondary = newStack<Integer>();
}
// O(1) Time
publicvoidenqueue(intitem) {
primary.push(item);
}
// O(N) Time
publicintdequeue() {
while (primary.size() != 1) {
secondary.push(primary.pop());
}
intremovedItem = primary.pop();
while (!secondary.isEmpty()) {
primary.push(secondary.pop());
}
returnremovedItem;
}
// O(N) Time
publicintfront() {
while (primary.size() != 1) {
secondary.push(primary.pop());
}
intfront = primary.peek();
while (!secondary.isEmpty()) {
primary.push(secondary.pop());
}
returnfront;
}
publicintsize() {
returnprimary.size();
}
}